//
//  LoginViewController.swift
//  上海微博
//
//  Created by zhangliming on 16/3/3.
//  Copyright © 2016年 zhangliming. All rights reserved.
//

import UIKit


import SVProgressHUD

class LoginViewController: UIViewController {

    private lazy var OAuthView = UIWebView()

    override func loadView() {

        view = OAuthView

        OAuthView.delegate = self

        view.backgroundColor = UIColor.greenColor()

        //设置导航栏标题，及按钮

        navigationItem.title = "登录"

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: .Done, target: self, action: "autoInput")

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancel")

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ///加载授权页面

        OAuthView.loadRequest(NetworkTools.shardTools.authriszeRequest)
    }

   }

//MARK:-UIWebViewDelegate代理方法判断是否登录

extension LoginViewController:UIWebViewDelegate{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

       // 如果请求地址中有服务器中的预留回调网址，就加载登录页面

        if let urlString = request.URL?.absoluteString where !urlString.hasPrefix(NetworkTools.shardTools.redirectURI){

            return true
        }

        //判断URL中是否包含code，如果包涵就取出code，如果不包含就取消授权

        guard let query = request.URL?.query where query.hasPrefix("code=")else {

            print("取消授权！")

            cancel()

            return false
        }

        // 3. 获取请求码
        let code = query.substringFromIndex("code=".endIndex)
      //  print("请求码 \(code)")

        //使用请求码获取数据

        NetworkTools.shardTools.loadAccessToken("authorization_code", code: code) { (result) -> () in

            guard let result = result else {

            SVProgressHUD.showInfoWithStatus("您的网络不给力！")

                return
            }

            let userAcceCount = userCountModel(dict:result)

            userAcceCount.saveUserAcceCount()

            print(userAcceCount)

        }
        return true
    }
}

extension LoginViewController {
       //MARK:-自动填充方法
   @objc private func autoInput (){

    let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
    "document.getElementById('passwd').value = 'qqq123';"

    OAuthView.stringByEvaluatingJavaScriptFromString(js)

    }

    //MARK:-取消按钮方法

    @objc private func cancel (){

        dismissViewControllerAnimated(true, completion: nil)


    }

    //MARK:-webView 代理方法控制网络指示器的启闭


    func webViewDidStartLoad(webView: UIWebView) {

        SVProgressHUD.setBackgroundColor(UIColor.greenColor())

        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
        
    }
}
